package br.com.sigad.servlets.documento;


import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import br.com.sigad.persistencia.dao.documento.DocumentoDAO;
import br.com.sigad.persistencia.model.DocumentoEntity;

/**
 * Servlet implementation class SalvarDocumento
 */
@WebServlet("/CarregarDocumento")
public class CarregarDocumento extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			DocumentoEntity documento = getParametros(request);
			
			DocumentoDAO dao = new DocumentoDAO();
			JSONObject documentoJS = dao.carregar(documento.getCodigo());

			
			
			String jsonString = JSONObject .toJSONString(documentoJS);
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(jsonString);
			return;
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("algo estranho");
	}

	private DocumentoEntity getParametros(HttpServletRequest request)
			throws java.text.ParseException {

		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader reader = request.getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		JSONParser parser = new JSONParser();
		JSONObject joUser = null;
		try {
			joUser = (JSONObject) parser.parse(sb.toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		DocumentoEntity dto = new DocumentoEntity();
		if (joUser != null) {
			dto.setCodigo(Long.parseLong((String) joUser.get("codigo")));
		}

		return dto;

	}
}
